﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mathematics.Parser
{
    public static class Interpreter
    {
        public static MathExpression InterpretLine(string raw)
        {
            var tokens = Lexer.LexLine(raw);
            var expression = MathParser.ParseExpression(tokens);
            return expression;
        }

        public static IEnumerable<MathExpression> InterpretText(string raw)
        {
            var tokenSet = Lexer.LexText(raw);
            var expression = MathParser.Parse(tokenSet);
            return expression;
        }

        public static IEnumerable<MathExpression> InterpretFile(string path)
        {
            var tokenSet = Lexer.LexFile(path);
            var expression = MathParser.Parse(tokenSet);
            return expression;
        }

        public static double? EvaluateLine(string raw)
        {
            var expression = InterpretLine(raw);
            return expression.Evaluate();
        }

        public static double? EvaluateText(string raw)
        {
            double? value = null;
            var expressions = InterpretText(raw);
            foreach (var e in expressions)
            {
                var v=e.Evaluate();
                if (v.HasValue)
                    value = v;
            }
            return value;
        }

        public static double? EvaluateFile(string path)
        {
            double? value = null;
            var expressions = InterpretFile(path);
            foreach (var e in expressions)
            {
                var v = e.Evaluate();
                if (v.HasValue)
                    value = v;
            }
            return value;
        }
    }
}
